var requestURL = 'http://139.9.229.30:8099/';
layui.config({
    base: "js/"
}).use(['form', 'layer', 'jquery', 'laypage'], function () {
    var form = layui.form(),
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        $ = layui.jquery;

    //加载页面数据-初始化
    var requestData = '';
    var nums = 5; //每页出现的数据量
    var requestDataCount = 0;//请求的数据量
    var requestDataPageNum = 1;//当前的PageNum
    // 请求数据
    requestDataFun(0, nums);

    //查询
    $(".search_btn").click(function () {
        if ($(".search_input").val() != '') {
            // 页面刷新
            requestDataFun(0, nums);
        } else {
            layer.msg("请输入需要查询的内容");
        }
    })

    //添加会员
    $(".usersAdd_btn").click(function () {
        var index = layui.layer.open({
            title: "添加维修记录",
            type: 2,
            content: "./main_manager_add.html",
            success: function (layero, index) {
                setTimeout(function () {
                    layui.layer.tips('点击此处返回维修列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function () {
            layui.layer.full(index);
        })
        layui.layer.full(index);
    })

    //刷新页面
    $(".refreshBtn").click(function () {
        requestDataFun(0, nums, "页面刷新成功");
    })

    //批量删除
    $(".batchDel").click(function () {
        var $checkbox = $('.users_list tbody input[type="checkbox"][name="checked"]');
        var $checked = $('.users_list tbody input[type="checkbox"][name="checked"]:checked');
        if ($checkbox.is(":checked")) {
            layer.confirm('确定删除选中的信息？', {icon: 3, title: '提示信息'}, function (index) {
                var index = layer.msg('删除中，请稍候', {icon: 16, time: false, shade: 0.8});
                setTimeout(function () {
                    //删除数据
                    var list = [];
                    for (var j = 0; j < $checked.length; j++) {
                        var text = $checked.eq(j).parents("tr").find(".users_del").attr("data-id");
                        list.push(text)
                    }
                    // 数据删除
                    batchDeleteData(list);
                    // 页面刷新
                    requestDataFun(0, nums);
                    // 关闭弹窗
                    layer.close(index);
                }, 2000);
            })
        } else {
            layer.msg("请选择需要删除的数据");
        }
    })

    //全选
    form.on('checkbox(allChoose)', function (data) {
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        child.each(function (index, item) {
            item.checked = data.elem.checked;
        });
        form.render('checkbox');
    });

    //通过判断文章是否全部选中来确定全选按钮是否选中
    form.on("checkbox(choose)", function (data) {
        var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
        var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
        if (childChecked.length == child.length) {
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
        } else {
            $(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
        }
        form.render('checkbox');
    })

    //操作
    $("body").on("click", ".users_edit", function () {  //编辑
        console.log("----------------》" + $(this).data('id'))
        var index = layui.layer.open({
            title: "修改记录",
            type: 2,
            content: "./main_manager_edit.html?id=" + $(this).data('id'),
            success: function (layero, index) {
                setTimeout(function () {
                    // layui.layer.tips('点击此处返回上一页', '.layui-layer-setwin .layui-layer-close', {
                    //     tips: 3
                    // });
                }, 500)
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function () {
            layui.layer.full(index);
        })
        layui.layer.full(index);
        // layer.alert('您点击了会员编辑按钮，由于是纯静态页面，所以暂时不存在编辑内容，后期会添加，敬请谅解。。。', {icon: 6, title: '文章编辑'});
    })

    //详情
    $("body").on("click", ".users_detail", function () {  //编辑
        var index = layui.layer.open({
            title: "查看记录详情",
            type: 2,
            content: "./main_manager_detail.html?id=" + $(this).data('id'),
            success: function (layero, index) {
                setTimeout(function () {
                    // layui.layer.tips('点击此处返回上一页', '.layui-layer-setwin .layui-layer-close', {
                    //     tips: 3
                    // });
                }, 500)
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function () {
            layui.layer.full(index);
        })
        layui.layer.full(index);
        // layer.alert('您点击了会员编辑按钮，由于是纯静态页面，所以暂时不存在编辑内容，后期会添加，敬请谅解。。。', {icon: 6, title: '文章编辑'});
    })



    $("body").on("click", ".users_del", function () {  //删除
        var _this = $(this);
        layer.confirm('确定删除此记录？', {icon: 3, title: '提示信息'}, function (index) {
            // 删除数据
            deleteData(_this.attr("data-id"));
            // 页面刷新
            requestDataFun(0, nums);
            // 关闭弹窗
            layer.close(index);
        });
    })

    // 删除数据
    function deleteData(currentId) {
        $.ajax({
            url: requestURL + "maintain/hist/delete",
            type: "POST",
            dataType: "json",
            data: {"id": currentId},
            success: function (data) {
                // 数据校验
                if (data.code != 200) {
                    layer.msg(data.msg);
                    return
                } else {
                    layer.alert('数据删除成功!', {icon: 6, title: '数据删除'});
                }
            }
        })
    }

    // 批量删除
    function batchDeleteData(list) {
        $.ajax({
            url: requestURL + "maintain/hist/deletes",
            type: "POST",
            dataType: "json",
            data: {"ids": list.join(',')},
            success: function (data) {
                // 数据校验
                if (data.code != 200) {
                    layer.msg(data.msg);
                    return
                } else {
                    layer.alert('数据删除成功!', {icon: 6, title: '数据删除'});
                }
            }
        })
    }

    // 渲染数据
    function renderData(currData) {
        var dataHtml = '';
        if (currData.length != 0) {
            for (var i = 0; i < currData.length; i++) {
                dataHtml += '<tr>'
                    + '<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
                    + '<td>' + currData[i].nickName + '</td>'
                    + '<td>' + currData[i].userPhone + '</td>'
                    + '<td>' + currData[i].carNumber + '</td>'
                    + '<td>' + currData[i].mainTime + '</td>'
                    + '<td>' + currData[i].mainType + '</td>'
                    + '<td>' + currData[i].mainCost + '</td>'
                    + '<td>' + mainPay(currData[i].mainPay) + '</td>'
                    + '<td>'
                    + '<a class="layui-btn layui-btn-mini users_edit" data-id="' + currData[i].id + '"><i class="iconfont icon-edit"></i> 编辑</a>'
                    + '<a class="layui-btn layui-btn-normal layui-btn-mini users_detail" data-id="' + currData[i].id + '"><i class="layui-icon">&#xe600;</i> 详情</a>'
                    + '<a class="layui-btn layui-btn-danger layui-btn-mini users_del" data-id="' + currData[i].id + '"><i class="layui-icon">&#xe640;</i> 删除</a>'
                    + '</td>'
                    + '</tr>';
            }
        } else {
            dataHtml = '<tr><td colspan="8">暂无数据</td></tr>';
        }
        return dataHtml;
    }

    // 请求数据
    function requestDataFun(page, size, context) {
        var selectStr = $(".search_input").val();
        var index = layer.msg('查询中，请稍候', {icon: 16, time: false, shade: 0.8});
        setTimeout(function () {
            $.ajax({
                url: requestURL + "maintain/hist/search?page=" + page + "&size=" + size,
                type: 'POST',
                header: {"Access-Control-Allow-Origin": requestURL},
                contentType: "application/json",
                mode: 'no-cors',
                headers: {
                    'Access-Control-Allow-Origin': requestURL,
                    'Content-Type': 'application/json',
                },
                withCredentials: true,
                xhrFields: {
                    withCredentials: true // 设置运行跨域操作
                },
                data: JSON.stringify({"searchKey": selectStr}),
                dataType: "json",
                success: function (data) {
                    // 数据校验
                    verfyData(data);
                    // 数据展示
                    for (var i = 0; i < requestData.length; i++) {
                        var usersStr = requestData[i];
                        if (selectStr!= '') {
                            //用户名
                            if (usersStr.nickName.indexOf(selectStr) > -1) {
                                usersStr["nickName"] = changeStr(selectStr, usersStr.nickName);
                            }
                            //用户电话
                            if (usersStr.userPhone.indexOf(selectStr) > -1) {
                                usersStr["userPhone"] = changeStr(selectStr,usersStr.userPhone);
                            }
                            //车牌
                            if (usersStr.carNumber.indexOf(selectStr) > -1) {
                                usersStr["carNumber"] = changeStr(selectStr, usersStr.carNumber);
                            }
                        }
                    }
                    pageList();
                    layer.close(index);
                }
            })
        }, 200);
    }
    // 文字添加颜色
    function changeStr(selectStr,data) {
        var dataStr = '';
        var showNum = data.split(eval("/" + selectStr + "/ig")).length - 1;
        if (showNum > 1) {
            for (var j = 0; j < showNum; j++) {
                dataStr += data.split(eval("/" + selectStr + "/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
            }
            dataStr += data.split(eval("/" + selectStr + "/ig"))[showNum];
            return dataStr;
        } else {
            dataStr = data.split(eval("/" + selectStr + "/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/" + selectStr + "/ig"))[1];
            return dataStr;
        }
    }
    // 数据分页
    function pageList() {
        var defaults = {
            cont: "page",
            curr: requestDataPageNum,
            pages: Math.ceil(requestDataCount / nums),
            jump: function (obj, first) {
                //得到了当前页，用于向服务端请求对应数据
                if (!first) {
                    requestDataFun(obj.curr, nums);
                } else {
                    $(".users_content").html(renderData(requestData));
                    $('.users_list thead input[type="checkbox"]').prop("checked", false);
                    form.render();
                }
            }
        }
        $.extend(defaults, {"size": nums}); //参数合并
        layui.laypage(defaults); //调用laypage组件渲染分页
    };
    // 数据校验
    function verfyData(data) {
        if (data.code != 200) {
            layer.msg(data.msg)
            return
        }
        requestData = data.data.list;
        requestDataCount = data.data.total;
        requestDataPageNum = data.data.pageNum;
    }

    function mainPay(data) {
        if (data == 0) {
            return "未支付"
        } else {
            return "已支付"
        }
    }

    function vipLevel(data) {
        //会员等级
        if (data == '0') {
            return "注册会员";
        } else if (data == '1') {
            return "中级会员";
        } else if (data == '2') {
            return "高级会员";
        } else if (data == '3') {
            return "超级会员";
        }
    }

    function vipStatus(data) {
        if (data == 1) {
            return "正常"
        } else {
            return "已注销"
        }
    }

    function userStatus(data) {
        if (data == 1) {
            return "正常"
        } else {
            return "已注销"
        }
    }
})